﻿using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SSPivot.AspNetCore.Extensions
{
    // 自定义Model Binder
    /// <summary>
    ///   public async Task<BaseWebApiResponse> Finance([ModelBinder(typeof(PostRequestBodyModelBinder))] ODataCompanyFinanceResponse model)
    ///   { 
    ///   return await ODataCollectService.PostCompanyFinanceTaskAsync(model);
    ///   }
    ///   现在无用
    ///   //context.Request.EnableBuffering(); //要写在操作Request.Body的最前边
    ///   context.Request.Body.Position = 0; //写操作Request.Body完成后
    /// </summary>
    public class PostRequestBodyModelBinder : IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var request = bindingContext.HttpContext.Request;

            var body = request.Body;
            // 读取请求体
            using (var reader = new StreamReader(body))
            {
                var content = reader.ReadToEnd();

                // 解析请求体，获取参数
                // 这里可以根据具体的请求体格式进行解析
                // 并将参数绑定到相应的模型对象上
                // 示例：将请求体内容绑定到一个字符串参数上
                Serilog.Log.Error($"{request.Path.ToString().ToUpper()}_POST参数1：{content}");
                bindingContext.Result = ModelBindingResult.Success(content);
            }

            return Task.CompletedTask;
        }
    }
}
